import { login, logout, getInfo, returnUserInformation } from '@/api/user'
import { getToken, setToken, removeToken, getRoles, setRoles, removeRole } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: getRoles(),
  id: null,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token // 将后端获取到的token赋值给状态变量state的token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  
  SET_ID: (state, id) => {
    state.id = id
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response;
        if(!data.isLogin){
          alert(data.message);
        }
     
          commit('SET_TOKEN', data.tokenInfo.tokenValue);
          commit("SET_ROLES", data.role);
          //id保存在这里
          commit("SET_ID",data.tokenInfo.loginId);
          console.log(data.tokenInfo.tokenValue);
          setToken(data.tokenInfo.tokenValue)
          setRoles(data.role);
     
     
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        console.log("user logout");
        commit('SET_TOKEN', '');
        commit('SET_ROLES', '');
        removeToken(); //删除Cookie中的token
        resetRouter();
        removeRole();//删除Cookie中的role
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', "")
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
